<template>
  <div class="register-container">
    <div class="register-card">
      <div class="logo-section">
        <img src="/风车.svg" alt="Logo" class="logo" />
        <h1 class="title">用户注册</h1>
        <p class="subtitle">填写信息创建您的博客账号</p>
      </div>

      <el-form
        ref="registerFormRef"
        :model="registerForm"
        :rules="rules"
        label-width="100px"
        class="register-form"
      >
        <el-form-item label="用户名" prop="username">
          <el-input
            v-model="registerForm.username"
            placeholder="请输入用户名（必填）"
            clearable
          />
        </el-form-item>

        <el-form-item label="密码" prop="password">
          <el-input
            v-model="registerForm.password"
            type="password"
            placeholder="请输入密码（必填）"
            show-password
            clearable
          />
        </el-form-item>

        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input
            v-model="registerForm.confirmPassword"
            type="password"
            placeholder="请再次输入密码"
            show-password
            clearable
          />
        </el-form-item>

        <el-form-item label="昵称" prop="nickname">
          <el-input
            v-model="registerForm.nickname"
            placeholder="请输入昵称（选填，默认为用户名）"
            clearable
          />
        </el-form-item>

        <el-form-item label="头像" prop="avatar" required>
          <ImageUpload
            v-model="avatarFile"
            upload-class="single-avatar"
            :max-size="2"
            show-tip
            tip-text="点击上传"
            @change="handleAvatarChange"
          />
        </el-form-item>

        <el-form-item label="性别" prop="gender">
          <el-radio-group v-model="registerForm.gender">
            <el-radio :label="0">未知</el-radio>
            <el-radio :label="1">男</el-radio>
            <el-radio :label="2">女</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="手机号" prop="phone">
          <el-input
            v-model="registerForm.phone"
            placeholder="请输入手机号（选填）"
            clearable
          />
        </el-form-item>

        <el-form-item label="邮箱" prop="email">
          <el-input
            v-model="registerForm.email"
            placeholder="请输入邮箱（选填）"
            clearable
          />
        </el-form-item>

        <el-form-item label="个人简介" prop="introduction">
          <el-input
            v-model="registerForm.introduction"
            type="textarea"
            :rows="3"
            placeholder="介绍一下自己吧（选填）"
          />
        </el-form-item>

        <el-form-item label="GitHub" prop="github">
          <el-input
            v-model="registerForm.github"
            placeholder="GitHub 地址（选填）"
            clearable
          />
        </el-form-item>

        <el-form-item label="Gitee" prop="gitee">
          <el-input
            v-model="registerForm.gitee"
            placeholder="Gitee 地址（选填）"
            clearable
          />
        </el-form-item>

        <el-form-item label="CSDN" prop="csdn">
          <el-input
            v-model="registerForm.csdn"
            placeholder="CSDN 地址（选填）"
            clearable
          />
        </el-form-item>

        <el-form-item>
          <el-button
            type="primary"
            :loading="loading"
            @click="handleRegister"
            class="register-btn"
          >
            立即注册
          </el-button>
          <el-button @click="goToLogin" class="back-btn">
            返回登录
          </el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from "vue"
import { useRouter } from "vue-router"
import { ElMessage } from "element-plus"
import type { FormInstance, FormRules } from "element-plus"
import { registerAPI, type RegisterData } from "@/api/web/auth"
import ImageUpload from "@/components/ImageUpload/index.vue"

const router = useRouter()
const registerFormRef = ref<FormInstance>()
const loading = ref(false)

// 头像文件
const avatarFile = ref<File | null>(null)

// 表单数据
const registerForm = reactive({
  username: "",
  password: "",
  confirmPassword: "",
  nickname: "",
  avatar: "",
  gender: 0,
  phone: "",
  email: "",
  introduction: "",
  github: "",
  gitee: "",
  csdn: ""
})

// 头像上传处理
const handleAvatarChange = (file: File | File[]) => {
  // 单图模式，file 是 File 类型
  if (file instanceof File) {
    avatarFile.value = file
    registerForm.avatar = file.name
  }
  
  // 手动触发表单验证
  registerFormRef.value?.validateField('avatar')
}

// 验证规则
const validateConfirmPassword = (rule: any, value: any, callback: any) => {
  if (value !== registerForm.password) {
    callback(new Error("两次输入的密码不一致"))
  } else {
    callback()
  }
}

const validateAvatar = (rule: any, value: any, callback: any) => {
  if (!avatarFile.value) {
    callback(new Error("请上传头像"))
  } else {
    callback()
  }
}

const rules = reactive<FormRules>({
  username: [
    { required: true, message: "请输入用户名", trigger: "blur" },
    { min: 3, max: 20, message: "用户名长度在 3 到 20 个字符", trigger: "blur" },
    { pattern: /^[a-zA-Z0-9_]+$/, message: "用户名只能包含字母、数字和下划线", trigger: "blur" }
  ],
  password: [
    { required: true, message: "请输入密码", trigger: "blur" },
    { min: 6, max: 20, message: "密码长度在 6 到 20 个字符", trigger: "blur" }
  ],
  confirmPassword: [
    { required: true, message: "请再次输入密码", trigger: "blur" },
    { validator: validateConfirmPassword, trigger: "blur" }
  ],
  avatar: [
    { required: true, validator: validateAvatar, trigger: "change" }
  ],
  phone: [
    { pattern: /^1[3-9]\d{9}$/, message: "请输入正确的手机号", trigger: "blur" }
  ],
  email: [
    { type: "email", message: "请输入正确的邮箱地址", trigger: "blur" }
  ]
})

/**
 * 处理注册
 */
const handleRegister = async () => {
  if (!registerFormRef.value) return

  try {
    await registerFormRef.value.validate()
    
    loading.value = true

    // 使用 FormData 发送数据（包含文件）
    const formData = new FormData()
    formData.append("username", registerForm.username)
    formData.append("password", registerForm.password)
    formData.append("nickname", registerForm.nickname)
    formData.append("gender", registerForm.gender.toString())
    formData.append("phone", registerForm.phone)
    formData.append("email", registerForm.email)
    formData.append("introduction", registerForm.introduction)
    formData.append("github", registerForm.github)
    formData.append("gitee", registerForm.gitee)
    formData.append("csdn", registerForm.csdn)
    
    // 添加头像文件
    if (avatarFile.value) {
      formData.append("avatar", avatarFile.value)
    }

    const res: any = await registerAPI(formData)
    
    if (res.code === 200) {
      ElMessage.success(res.message || "注册成功！即将跳转到登录页面")
      
      // 延迟跳转到登录页面
      setTimeout(() => {
        router.push("/pseudo-login")
      }, 1500)
    } else {
      ElMessage.error(res.message || "注册失败，请稍后重试")
    }
  } catch (error: any) {
    console.error("注册错误:", error)
    if (error.response?.data?.message) {
      ElMessage.error(error.response.data.message)
    } else if (error instanceof Error && error.message) {
      // 表单验证失败
      return
    } else {
      ElMessage.error("注册失败，请稍后重试")
    }
  } finally {
    loading.value = false
  }
}

/**
 * 返回登录页面
 */
const goToLogin = () => {
  router.push("/pseudo-login")
}
</script>

<style scoped lang="scss">
.register-container {
  min-height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background: var(--gradient-primary);
  padding: 40px 20px;
  position: relative;
  overflow: hidden;

  // 背景动画效果
  &::before {
    content: "";
    position: absolute;
    top: -50%;
    left: -50%;
    width: 200%;
    height: 200%;
    background: radial-gradient(
      circle,
      rgba(255, 255, 255, 0.1) 1px,
      transparent 1px
    );
    background-size: 50px 50px;
    animation: backgroundMove 20s linear infinite;
  }

  @keyframes backgroundMove {
    0% {
      transform: translate(0, 0);
    }
    100% {
      transform: translate(50px, 50px);
    }
  }
}

.register-card {
  width: 100%;
  max-width: 700px;
  background: white;
  border-radius: 20px;
  padding: 40px;
  box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
  position: relative;
  z-index: 1;
  max-height: 90vh;
  overflow-y: auto;
  overflow-x: hidden;
  scroll-behavior: smooth;

//   // 美化滚动条
//   &::-webkit-scrollbar {
//     width: 8px;
//   }

//   &::-webkit-scrollbar-track {
//     background: rgba(0, 0, 0, 0.03);
//     border-radius: 4px;
//     margin: 10px 0;
//   }

//   &::-webkit-scrollbar-thumb {
//     background: linear-gradient(180deg, #667eea 0%, #764ba2 100%);
//     border-radius: 4px;
//     transition: all 0.3s ease;

//     &:hover {
//       background: linear-gradient(180deg, #5568d3 0%, #653a8b 100%);
//       box-shadow: 0 0 6px rgba(102, 126, 234, 0.4);
//     }

//     &:active {
//       background: linear-gradient(180deg, #4a5bc4 0%, #552f7a 100%);
//     }
//   }

//   // Firefox 滚动条美化
//   scrollbar-width: thin;
//   scrollbar-color: #667eea rgba(0, 0, 0, 0.03);

  @media (max-width: 768px) {
    padding: 30px 20px;
    max-width: 500px;
  }
}

.logo-section {
  text-align: center;
  margin-bottom: 30px;

  .logo {
    width: 60px;
    height: 60px;
    margin-bottom: 15px;
    animation: rotate 20s linear infinite;
  }

  @keyframes rotate {
    from {
      transform: rotate(0deg);
    }
    to {
      transform: rotate(360deg);
    }
  }

  .title {
    font-size: 26px;
    font-weight: bold;
    color: #333;
    margin-bottom: 8px;
    background: var(--gradient-primary);
    -webkit-background-clip: text;
    -webkit-text-fill-color: transparent;
    background-clip: text;
  }

  .subtitle {
    font-size: 14px;
    color: #666;
    margin: 0;
  }
}

.register-form {
  .register-btn {
    width: 48%;
    height: 45px;
    font-size: 16px;
    font-weight: 600;
    background: var(--gradient-primary);
    border: none;
    transition: all 0.3s;

    &:hover {
      transform: translateY(-2px);
      box-shadow: 0 10px 20px rgba(102, 126, 234, 0.4);
    }

    &:active {
      transform: translateY(0);
    }
  }

  .back-btn {
    width: 48%;
    height: 45px;
    font-size: 16px;
    margin-left: 4%;
  }
}

:deep(.el-form-item__label) {
  font-weight: 600;
  color: #333;
}

:deep(.el-input__wrapper) {
  height: 40px;
}

:deep(.el-textarea__inner) {
  font-family: inherit;
}
</style>

